package secret

import (
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/informers"
	"kubeconsole/api"
	"kubeconsole/apiserver/query"
	"kubeconsole/models/resources/v1alpha3"
)

type secretGetter struct {
	informers informers.SharedInformerFactory
}

func New(informers informers.SharedInformerFactory) v1alpha3.Interface {
	return &secretGetter{informers: informers}
}

func (s *secretGetter) Get(namespace, name string) (runtime.Object, error) {
	return s.informers.Core().V1().Secrets().Lister().Secrets(namespace).Get(name)
}

func (s *secretGetter) List(namespace string, query *query.Query) (*api.ListResult, error) {
	all, err := s.informers.Core().V1().Secrets().Lister().Secrets(namespace).List(query.Selector())

	if err != nil {
		return nil, err
	}

	var result []runtime.Object
	for _, app := range all {
		result = append(result, app)
	}

	return v1alpha3.DefaultList(result, query, s.compare, s.filter), nil
}

func (s *secretGetter) compare(left runtime.Object, right runtime.Object, field query.Field) bool {

	leftSecret, ok := left.(*corev1.Secret)
	if !ok {
		return false
	}

	rightSecret, ok := right.(*corev1.Secret)
	if !ok {
		return false
	}

	return v1alpha3.DefaultObjectMetaCompare(leftSecret.ObjectMeta, rightSecret.ObjectMeta, field)
}

func (s *secretGetter) filter(object runtime.Object, filter query.Filter) bool {
	secret, ok := object.(*corev1.Secret)
	if !ok {
		return false
	}

	return v1alpha3.DefaultObjectMetaFilter(secret.ObjectMeta, filter)
}
